package main

import (
	"gitee.com/zaiqiang231/go-base-app/base_app"
	baseLog "gitee.com/zaiqiang231/go-base-app/base_app/log"
	baseRpc "gitee.com/zaiqiang231/go-base-app/base_app/rpc"
	baseStore "gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/zcamp-service-file/app/config"
	"gitee.com/zaiqiang231/zcamp-service-file/app/http"
	"gitee.com/zaiqiang231/zcamp-service-file/app/rpc"
	remoteRpc "gitee.com/zaiqiang231/zcamp-service-file/app/rpc/remote"
	"github.com/fatih/color"
	"github.com/spf13/viper"
	"golang.org/x/sync/errgroup"
)

func main() {
	base_app.NewApp(
		config.ServiceName,
		initConfig,
		base_app.WithCmdDescription("base session service"),
		base_app.WithRunFunc(run),
	).Run()
}

// 解析配置
func initConfig(a *base_app.App) {
	baseLog.Debugf("开始读取配置")
	if err := viper.Unmarshal(config.GlobalAppConfig); err != nil {
		baseLog.Fatalf("读取配置失败: %v", err)
	}
	baseLog.Debugf("读取配置: GlobalConfig = %v", config.GlobalAppConfig)
	var err error
	//初始化mysql
	_, err = baseStore.InitDataStore(config.GlobalAppConfig.MysqlConfig)
	if err != nil {
		baseLog.Errorf("failed to initStore : %v", err)
	}

	//初始化redis
	_, err = baseStore.InitRedisStore(config.GlobalAppConfig.RedisConfig)
	if err != nil {
		baseLog.Errorf("failed to initStore : %v", err)
	}

	//session rpc
	_, err = remoteRpc.InitSessionRpc("192.168.109.133:36002")
	//_, err = remoteRpc.InitSessionRpc("127.0.0.1:6002")
	if err != nil {
		baseLog.Errorf("failed to init rpc : %v", err)
	}

}

// 配置已经读取完成后，再启动服务
func run(basename string) error {
	baseLog.Infof("%v %v 应用启动", color.GreenString("LoveSport:"), basename)
	defer func() {
		baseLog.Infof("%v %v 应用退出", color.GreenString("LoveSport:"), basename)
	}()

	var eg errgroup.Group
	gs := base_app.NewGracefulShutdown()
	//http 服务
	base_app.CreateAPIServer(
		basename,
		base_app.WithServerConfig(config.GlobalAppConfig.ServerConfig),
		base_app.WithGracefulShutdown(gs),
		base_app.WithRouter(http.InitRouter),
	).PrepareRun().Run(&eg)
	//rpc 服务
	baseRpc.CreateGrpcServer(basename+" rpc",
		baseRpc.WithAddress(config.GlobalAppConfig.GRpcServerConfig.Addr),
		baseRpc.WithGracefulShutdown(gs),
		baseRpc.WithGRpcServer(rpc.InitGRpc),
	).PrepareRun().Run(&eg)

	//优雅关闭监听启动
	if err := gs.Start(); err != nil {
		baseLog.Fatalf("%v start shutdown manager failed: %s", basename, err.Error())
	}

	if err := eg.Wait(); err != nil {
		baseLog.Fatalf("ApiServer eg.Wait() err: ", err.Error())
	}

	return nil
}
